package com.mogist.hqc.module.route.ui

import android.app.Dialog
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Point
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.provider.MediaStore
import android.support.design.widget.TabLayout
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import butterknife.OnClick
import butterknife.Optional
import com.baidu.mapapi.map.*
import com.baidu.mapapi.model.LatLng
import com.chad.library.adapter.base.BaseQuickAdapter
import com.github.florent37.viewanimator.ViewAnimator
import com.mogist.hqc.R
import com.mogist.hqc.base.BaseMVPActivity
import com.mogist.hqc.entitys.BaseModel
import com.mogist.hqc.entitys.response.*
import com.mogist.hqc.module.common.ui.CommentListActivity
import com.mogist.hqc.module.main.ui.SearchActivity
import com.mogist.hqc.module.place.ui.ScenicActivity
import com.mogist.hqc.module.product.adapter.ProductDetailAdapter
import com.mogist.hqc.module.route.adapter.RouteDayAdapter
import com.mogist.hqc.module.route.adapter.RouteInfoAdapter
import com.mogist.hqc.module.route.contract.RouteMainContract
import com.mogist.hqc.module.route.presenter.RouteMainPresenter
import com.mogist.hqc.mvp.HttpDto
import com.mogist.hqc.util.Constant
import com.mogist.hqc.util.Constant.DOUBLE_DISTANCE
import com.mogist.hqc.util.DistanceUtil
import com.mogist.hqc.util.Util
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_route_main.*
import kotlinx.android.synthetic.main.include_title.*
import org.greenrobot.eventbus.Subscribe
import talex.zsw.basecore.util.*
import talex.zsw.basecore.view.dialog.sweetalertdialog.SweetAlertDialog
import talex.zsw.basecore.view.other.RxToast
import talex.zsw.basecore.view.popupwindow.PopLayout
import talex.zsw.basecore.view.recyleview.DividerItemDecoration

/**
 * 作用：线路首页
 * 作者：赵小白 email:vvtale@gmail.com  
 * 修改人：
 * 修改时间：
 * 修改备注：
 */
class RouteMainActivity : BaseMVPActivity<RouteMainContract.Presenter>(), RouteMainContract.View
{
    private var id = ""
    private var isFirst = true
    override fun initArgs(intent: Intent)
    {
        intent.getStringExtra("id")
                ?.let {
                    id = it
                }
    }

    override fun initView()
    {
        setContentView(R.layout.activity_route_main)
        mPresenter = RouteMainPresenter(this)
    }

    override fun initData()
    {
        mTitleBar.setTitle("行程路线")
        mTitleBar.setRightIV(R.drawable.i_search) {
            val intent = Intent(this@RouteMainActivity, SearchActivity::class.java)
            intent.putExtra("type", "ROUTE")
            intent.putExtra("fromMain", false)
            start(intent)
        }
        initRecyclerView()
        initMap()

        if (RegTool.isEmpty(id))
        {
            mTabLayout.visibility = View.VISIBLE
            mTvTitle.visibility = View.GONE
            mainRoute()
        }
        else
        {
            mTabLayout.visibility = View.GONE
            mTvTitle.visibility = View.VISIBLE
            getRouteDetail(id)
        }
    }

    @Optional
    @OnClick(R.id.mLLFoot, R.id.mIvCloseType, R.id.mLLTypeDetail, R.id.mRvType)
    fun onViewClicked(view: View)
    {
        if (!isFastClick)
        {
            when (view.id)
            {
                R.id.mLLFoot                          ->
                {
                    mLLTypeDetail.visibility = View.VISIBLE
                }
                R.id.mIvCloseType, R.id.mLLTypeDetail ->
                {
                    mLLTypeDetail.visibility = View.GONE
                }
            }
        }
    }

    // ============================== 功能抽屉 start ==============================
    @Optional
    @OnClick(R.id.mIvItemClose,
             R.id.mIvItemStar,
             R.id.mTvItemStar,
             R.id.mIvItemComment,
             R.id.mTvItemComment,
             R.id.mIvItemShare,
             R.id.mIvItemMore,
             R.id.mIvSelect,
             R.id.mIvItemShow)
    fun onViewItemsClicked(view: View)
    {
        if (!isFastClick)
        {
            when (view.id)
            {
                R.id.mIvItemClose                        ->
                { // 关闭
                    if (!isAnim)
                    {
                        showItems(false)
                    }
                }
                R.id.mIvItemStar, R.id.mTvItemStar       ->
                { // 收藏
                    //type:COL收藏 NOCOL取消收藏 colType:PLACE地点ROUTE线路PRODUCT产品
                    val body = BaseModel(true)
                    body.type = "COL"
                    body.colType = "ROUTE"
                    body.pdtId = id
                    mPresenter.getData(HttpDto(Constant.COLLECT_ADD,
                                               body,
                                               true).setShowError(false))
                }
                R.id.mIvItemComment, R.id.mTvItemComment ->
                { // 评论
                    if (!isAnim)
                    {
                        val intent = Intent(this@RouteMainActivity, CommentListActivity::class.java)
                        intent.putExtra("id", id)
                        intent.putExtra("type", 1)
                        start(intent)
                        overridePendingTransition(R.anim.activity_bottom_open, 0)
                        showItems(false)
                    }
                }
                R.id.mIvItemShare                        ->
                { // 线路分享
                    if (!isAnim)
                    {
                        showItems(false)
                        mBaiduMap?.snapshot { mapBitmap ->
                            if (mTabLayout.visibility == View.VISIBLE)
                            {
                                showShareDialog(Util.createScreenShotBitmap(this@RouteMainActivity,
                                                                            Util.mosaicBitmapVertical(
                                                                                    BitmapTool.view2Bitmap(
                                                                                            mTabLayout),
                                                                                    mapBitmap,
                                                                                    BitmapTool.view2Bitmap(
                                                                                            mLLDetail))))
                            }
                            else
                            {
                                showShareDialog(Util.createScreenShotBitmap(this@RouteMainActivity,
                                                                            Util.mosaicBitmapVertical(
                                                                                    BitmapTool.view2Bitmap(
                                                                                            mTvTitle),
                                                                                    mapBitmap,
                                                                                    BitmapTool.view2Bitmap(
                                                                                            mLLDetail))))
                            }
                        }
                    }
                }
                R.id.mIvItemMore                         ->
                { // 线路更多 - 租车
                    showPop()
                }
                R.id.mIvItemShow                         ->
                { // 打开
                    if (!isAnim)
                    {
                        showItems(true)
                    }
                }
                R.id.mIvSelect                           ->
                { // 回到选中的点
                    selectMarker?.let {
                        mBaiduMap?.setMapStatus(MapStatusUpdateFactory.newLatLng(it.position))
                    }
                }
            }
        }
    }

    var popLayout: PopLayout? = null

    private fun showPop()
    {
        popLayout
                ?: let {
                    // 显示一个自定义View的pop
                    popLayout =
                            PopLayout(this@RouteMainActivity,
                                      ViewGroup.LayoutParams.WRAP_CONTENT,
                                      ViewGroup.LayoutParams.WRAP_CONTENT,
                                      R.layout.view_pop_route)
                    popLayout?.contentView!!.findViewById<TextView>(R.id.vTvMore)
                            .setOnClickListener {
                                if (!isAnim)
                                {
                                    start(IntentTool.getWebIntent(Constant.RENT_CAR))
                                    popLayout?.dismiss()
                                    showItems(false)
                                }
                            }
                }
        popLayout?.show(mIvItemMore)
    }

    private var isShow = true
    private var isAnim = false

    private fun showItems(flag: Boolean)
    {
        try
        {
            val dp = DimenTool.dp2px(192f)
            isAnim = true
            if (flag)
            { // 显示的动画
                ViewAnimator.animate(mLLAnim)
                        .translationX(dp.toFloat(), 0f)
                        .duration(500)
                        .start()
                        .onStop {
                            mIvItemClose.visibility = View.VISIBLE
                            mIvItemShow.visibility = View.GONE
                            isShow = true
                            isAnim = false
                        }
            }
            else
            { // 隐藏动画
                ViewAnimator.animate(mLLAnim)
                        .translationX(0f, dp.toFloat())
                        .duration(500)
                        .start()
                        .onStop {
                            mIvItemClose.visibility = View.GONE
                            mIvItemShow.visibility = View.VISIBLE
                            isShow = false
                            isAnim = false
                        }
            }
        }
        catch (e: Exception)
        {
            isAnim = false
            isShow = mIvItemClose.visibility == View.VISIBLE
            e.printStackTrace()
        }
    }
    // ============================== 功能抽屉 end ==============================
    // --------------- 获取推荐列表 ---------------
    /** 首页线路推荐 **/
    private fun mainRoute()
    {
        val body = BaseModel(true)
        mPresenter.getData(HttpDto(Constant.MAIN_ROUTE,
                                   body).setType(HttpDto.GET).setFinish(true).setErrorTitle("获取推荐线路失败"))
    }

    override fun bindRoute(data: MainRouteListVo)
    {
        if (data.list != null && data.list.isNotEmpty())
        {
            initTabLayout(data.list)
        }
        else
        {
            showDialog(SweetAlertDialog.ERROR_TYPE, "获取推荐线路失败", "暂无推荐列表")
        }
    }

    // --------------- 获取线路详情 ---------------
    private fun getRouteDetail(id: String)
    {
        this.id = id
        val body = BaseModel()
        body.projectId = id
        mPresenter.getData(HttpDto(Constant.TYPE_DETAIL, body).setType(HttpDto.GET))
    }

    private var listData: ArrayList<ProductDetailItemVo> = arrayListOf()
    private var listRouteDayStr: ArrayList<RouteDayVo> = arrayListOf()
    private var listRouteInfos: ArrayList<ArrayList<RouteDetailItemVo>> = arrayListOf()

    override fun bindRouteDetail(data: TypeDetailVo)
    {
        mTvTitle.text = data.platfromProject.proName
        mTvItemComment.text = data.platfromProject.sayNum.toString()
        // 是否有图文详情图文详情
        if (data.projectDetailList != null && data.projectDetailList.isNotEmpty())
        {
            listData = arrayListOf()
            mLLFoot.visibility = View.VISIBLE
            for (item in data.projectDetailList)
            {
                addItem(item.type, item.conUrl, item.videoUrl)
            }
            mAdapter.replaceData(listData)
        }
        // 日期数据分割
        if (data.routeInfoList != null && data.routeInfoList.isNotEmpty())
        {
            listRouteDayStr = arrayListOf()
            listRouteInfos = arrayListOf()
            var temp = ""
            var longitude = "0"
            var latitude = "0"
            listRouteDayStr.add(RouteDayVo("全程", true))
            var list: ArrayList<RouteDetailItemVo> = arrayListOf()
            markerList = arrayListOf()
            points = arrayListOf()
            mBaiduMap?.clear()
            var pos = 0
            for (item in data.routeInfoList)
            {
                var str = item.stepName
                val strs = item.stepName.split("-")
                if (strs.isNotEmpty())
                {
                    str = strs[0]
                }
                if (temp == str)
                {
                    // 计算距离
                    list.add(RouteDetailItemVo(2,
                                               DistanceUtil.getDistance(latitude,
                                                                        longitude,
                                                                        item.latitude,
                                                                        item.longitude),
                                               pos))
                    longitude = item.longitude
                    latitude = item.latitude
                    list.add(RouteDetailItemVo(item, pos))
                    pos++
                }
                else
                { // 首节点
                    if (list.isNotEmpty())
                    {
                        listRouteInfos.add(list)
                    }
                    temp = str
                    list = arrayListOf()
                    listRouteDayStr.add(RouteDayVo(temp))
                    list.add(RouteDetailItemVo(0, temp, pos))
                    list.add(RouteDetailItemVo(item, pos))
                    longitude = item.longitude
                    latitude = item.latitude
                    pos++
                }
            }
            if (list.isNotEmpty())
            {
                listRouteInfos.add(list)
            }
        }
        selectMarkerPos = -1
        mBaiduMap?.let {
            if (data.routeInfoList.size > 0)
            {
                val point =
                        LatLng(MathTool.mul(data.routeInfoList[0].latitude, "1"),
                               MathTool.mul(data.routeInfoList[0].longitude, "1"))
                //构建Marker图标
                val bundle = Bundle()
                bundle.putInt("pos", -1)
                //构建MarkerOption，用于在地图上添加Marker
                val option =
                        MarkerOptions().position(point)
                                .extraInfo(bundle)
                option.icon(markerIconBig)
                //在地图上添加Marker，并显示
                selectMarkerPos = -0
                selectMarker = mBaiduMap!!.addOverlay(option) as Marker
            }
        }
        mIvSelect.visibility = View.GONE
        bindAll()

        adapterDay.replaceData(listRouteDayStr)
        adapterDay.setTemp(0)
        mHandler.sendEmptyMessageDelayed(0, 1000)
    }

    var deletePos = 0
    private fun bindAll()
    {
        var totalPos = 0
        deletePos = 0
        selectMarker = null
        adapterInfo.replaceData(arrayListOf())
        listRouteInfos.forEach {
            adapterInfo.addData(it)
            for (vo in it)
            {
                if (vo.itemType == 1)
                {
                    // 地图添加标记点和连线
                    addMark(vo.data, totalPos)
                }
                totalPos++
            }
        }
        layoutManager.scrollToPosition(0)
        addLine()
        if (adapterInfo.data.size > 1 && adapterInfo.data[1].itemType == 1)
        {
            moveTo(adapterInfo.data[1].data.latitude, adapterInfo.data[1].data.longitude)
        }
    }

    private fun bindDayInfo(pos: Int)
    {
        markerList = arrayListOf()
        points = arrayListOf()
        selectMarker = null
        mBaiduMap?.clear()
        var totalPos = 0
        adapterInfo.replaceData(arrayListOf())
        adapterInfo.addData(listRouteInfos[pos])
        layoutManager.scrollToPosition(0)
        for (vo in listRouteInfos[pos])
        {
            if (vo.itemType == 1)
            {
                // 地图添加标记点和连线
                addMark(vo.data, totalPos)
            }
            totalPos++
        }
        addLine()
        if (adapterInfo.data.size > 1 && adapterInfo.data[1].itemType == 1)
        {
            moveTo(adapterInfo.data[1].data.latitude, adapterInfo.data[1].data.longitude)
            deletePos = adapterInfo.data[1].pos
            selectMarkerPos = -1
            mBaiduMap?.let {
                val point =
                        LatLng(MathTool.mul(adapterInfo.data[1].data.latitude, "1"),
                               MathTool.mul(adapterInfo.data[1].data.longitude, "1"))
                //构建Marker图标
                val bundle = Bundle()
                bundle.putInt("pos", -1)
                //构建MarkerOption，用于在地图上添加Marker
                val option =
                        MarkerOptions().position(point)
                                .extraInfo(bundle)
                option.icon(markerIconBig)
                //在地图上添加Marker，并显示
                selectMarkerPos = -0
                selectMarker = mBaiduMap!!.addOverlay(option) as Marker
            }
        }
    }

    private fun addItem(type: String?, info: String?, video: String?)
    { // 0:Tab  1:图片  2:文字  3:视频  4:行程
        if (type == "img")
        {
            listData.add(ProductDetailItemVo(1, info))
        }
        else if (type == "text")
        {
            listData.add(ProductDetailItemVo(2, info))
        }
        else if (type == "video")
        {
            val item = ProductDetailItemVo(3, info)
            item.videoUrl = video
            listData.add(item)
        }
    }

    override fun starSuccess()
    {
        RxToast.success("收藏成功")
        showItems(false)
        mIvItemStar.setImageResource(R.drawable.i_star_yes)
    }

    // --------------- RecyclerView ---------------
    private val adapterDay = RouteDayAdapter()
    private val adapterInfo = RouteInfoAdapter(arrayListOf())
    private val mAdapter = ProductDetailAdapter(arrayListOf())
    private val layoutManager = LinearLayoutManager(this@RouteMainActivity, 0, false)
    private fun initRecyclerView()
    {
        // 日期
        adapterDay.setOnItemClickListener { adapter, view, position ->
            if (!isFastClick)
            {
                adapterDay.changeSelect(position)
                if (position == 0)
                {
                    bindAll()
                }
                else
                {
                    bindDayInfo(position - 1)
                }
            }
        }
        adapterDay.openLoadAnimation(BaseQuickAdapter.ALPHAIN)
        mRvDay.addItemDecoration(DividerItemDecoration(DividerItemDecoration.HORIZONTAL_LIST,
                                                       R.color.transparent))
        mRvDay.layoutManager = LinearLayoutManager(this@RouteMainActivity, 0, false)
        mRvDay.adapter = adapterDay
        // 日线路列表
        adapterInfo.setOnItemChildClickListener { adapter, view, position ->
            if (!isFastClick)
            {
                val vo = adapter.getItem(position) as RouteDetailItemVo
                val intent = Intent(this@RouteMainActivity, ScenicActivity::class.java)
                intent.putExtra("id", vo.data.linkId)
                startActivity(intent)
            }
        }
        adapterInfo.openLoadAnimation(BaseQuickAdapter.ALPHAIN)
        mRecyclerView.addItemDecoration(DividerItemDecoration(DividerItemDecoration.HORIZONTAL_LIST,
                                                              R.color.transparent))
        mRecyclerView.layoutManager = layoutManager
        mRecyclerView.adapter = adapterInfo

        mRecyclerView.viewTreeObserver.addOnScrollChangedListener {
            if (!isFirst && isShow && !isAnim)
            {
                showItems(false)
            }
            val n = layoutManager.findFirstVisibleItemPosition()
            if (0 <= n && n < adapterInfo.data.size)
            {
                val vo = adapterInfo.getItem(n)
                vo?.pos?.let { changeMarker(it) }
            }
        }
        // 详情
        mRvType.addItemDecoration(DividerItemDecoration(DividerItemDecoration.VERTICAL_LIST,
                                                        R.color.transparent))
        mRvType.layoutManager = LinearLayoutManager(this@RouteMainActivity)
        mRvType.adapter = mAdapter
    }

    // --------------- TabLayout ---------------
    private var ids = arrayListOf<String>()

    private fun initTabLayout(list: List<MainRouteVo>)
    {
        ids = arrayListOf()
        mTabLayout.removeAllTabs()
        list.forEach {
            mTabLayout.addTab(mTabLayout.newTab().setText("    ${it.proName}    "))
            ids.add(it.id)
        }
        mTabLayout.tabMode = TabLayout.MODE_SCROLLABLE
        mTabLayout.addOnTabSelectedListener(selectListener)
        getRouteDetail(ids[0])
    }

    private val selectListener = object : TabLayout.BaseOnTabSelectedListener<TabLayout.Tab>
    {
        override fun onTabSelected(tab: TabLayout.Tab)
        {
            getRouteDetail(ids[tab.position])
        }

        override fun onTabUnselected(tab: TabLayout.Tab)
        {

        }

        override fun onTabReselected(tab: TabLayout.Tab)
        {

        }
    }
    // ============================== 地图 start ==============================
    private var mBaiduMap: BaiduMap? = null

    private fun initMap()
    {
        mBaiduMap = mMapView.map
        val builder1 = MapStatus.Builder()
        builder1.overlook(0f)
        mBaiduMap?.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder1.build()))
        initListener()
    }

    private fun initListener()
    {
        val listener = object : BaiduMap.OnMapStatusChangeListener
        {
            /** 手势操作地图，设置地图状态等操作导致地图状态开始改变。 */
            override fun onMapStatusChangeStart(p0: MapStatus?)
            {
            }

            /** 手势操作地图，设置地图状态等操作导致地图状态开始改变。 */
            //用户手势触发导致的地图状态改变,比如双击、拖拽、滑动底图
            //int REASON_GESTURE = 1;
            //SDK导致的地图状态改变, 比如点击缩放控件、指南针图标
            //int REASON_API_ANIMATION = 2;
            //开发者调用,导致的地图状态改变
            //int REASON_DEVELOPER_ANIMATION = 3;
            override fun onMapStatusChangeStart(p0: MapStatus, p1: Int)
            {
            }

            /** 地图状态变化中 */
            override fun onMapStatusChange(p0: MapStatus?)
            {
            }

            /** 地图状态改变结束 */
            override fun onMapStatusChangeFinish(p0: MapStatus)
            {
                if (!isFirst && isShow && !isAnim)
                {
                    showItems(false)
                }
                selectMarker?.let {
                    if (DistanceUtil.getDistance(p0.target, it.position) > DOUBLE_DISTANCE)
                    {
                        mIvSelect.visibility = View.VISIBLE
                    }
                    else
                    {
                        mIvSelect.visibility = View.GONE
                    }
                }
            }
        }
        mBaiduMap?.setOnMapStatusChangeListener(listener)
        mBaiduMap?.setOnMapLoadedCallback { mMapView.zoomControlsPosition = Point(0, 10) }
        mBaiduMap?.setOnMarkerClickListener { marker ->
            val bundle = marker.extraInfo
            val pos = bundle.getInt("pos")
            try
            {
                if (pos >= 0)
                {
                    layoutManager.scrollToPositionWithOffset(pos, 0)
                    layoutManager.stackFromEnd = true
                }
            }
            catch (e: Exception)
            {
                e.printStackTrace()
            }
            true
        }
    }

    private var markerList: ArrayList<Marker> = arrayListOf()
    private fun addMark(data: TypeDetailVo.RouteInfoListEntity, pos: Int)
    {
        mBaiduMap?.let {
            //定义Maker坐标点
            val point = LatLng(MathTool.mul(data.latitude, "1"), MathTool.mul(data.longitude, "1"))
            points.add(point)
            //构建Marker图标
            val bundle = Bundle()
            bundle.putSerializable("data", data)
            bundle.putInt("pos", pos)
            //构建MarkerOption，用于在地图上添加Marker
            val option =
                    MarkerOptions().position(point)
                            .extraInfo(bundle)
                            .icon(getViewBitmap(data.stepNum.toString()))
            //在地图上添加Marker，并显示
            markerList.add(mBaiduMap!!.addOverlay(option) as Marker)
        }
    }

    private val markerIconBig = BitmapDescriptorFactory.fromResource(R.drawable.i_mark2)
    private var selectMarkerPos = -1
    private var selectMarker: Marker? = null
    private fun changeMarker(pos: Int)
    {
        val x = pos - deletePos
        if (selectMarkerPos != x)
        {
            try
            {
                selectMarker?.position = markerList[x].position
                selectMarkerPos = x
                mBaiduMap?.setMapStatus(MapStatusUpdateFactory.newLatLng(markerList[x].position))
            }
            catch (e: Exception)
            {
                e.printStackTrace()
            }
        }
    }

    private fun getViewBitmap(text: String): BitmapDescriptor
    {
        val addViewContent =
                LayoutInflater.from(this)
                        .inflate(R.layout.view_marker, null)
        val textView = addViewContent.findViewById<TextView>(R.id.vTvPos)
        textView.text = text
        addViewContent.isDrawingCacheEnabled = true
        addViewContent.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                               View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
        addViewContent.layout(0, 0, addViewContent.measuredWidth, addViewContent.measuredHeight)
        addViewContent.buildDrawingCache()
        return BitmapDescriptorFactory.fromView(addViewContent)
    }

    var points: ArrayList<LatLng> = arrayListOf()
    private fun addLine()
    {
        if (points != null && points.size > 1)
        {
            //设置折线的属性
            val mOverlayOptions =
                    PolylineOptions().width(5)
                            .color(ColorTool.getColorById(R.color.text_green))
                            .points(points)
            //在地图上绘制折线
            mBaiduMap?.addOverlay(mOverlayOptions)
        }
    }

    private fun moveTo(lat: String, lon: String)
    {
        val point = LatLng(MathTool.mul(lat, "1"), MathTool.mul(lon, "1"))
        mBaiduMap?.setMapStatus(MapStatusUpdateFactory.newLatLng(point))
    }

    override fun onResume()
    {
        super.onResume()
        // 在activity执行onResume时必须调用mMapView. onResume ()
        mMapView.onResume()
    }

    override fun onPause()
    {
        super.onPause()
        // 在activity执行onPause时必须调用mMapView. onPause ()
        mMapView.onPause()
    }

    override fun onDestroy()
    {
        super.onDestroy()
        // 在activity执行onDestroy时必须调用mMapView.onDestroy()
        mMapView.onDestroy()
        mHandler.removeMessages(0)
    }

    // ============================== 地图 end ==============================
    // --------------- 分享 ----------------
    private var shareDialog: Dialog? = null
    private var dImage: ImageView? = null
    private fun showShareDialog(bitmap: Bitmap)
    {
        shareDialog
                ?: let {
                    shareDialog = Dialog(this@RouteMainActivity, R.style.dialog)
                    shareDialog?.setContentView(R.layout.dialog_share)
                    shareDialog?.setCanceledOnTouchOutside(false)
                    val display = window.windowManager.defaultDisplay
                    val layoutParams: WindowManager.LayoutParams = shareDialog?.window!!.attributes
                    layoutParams.width = (display.width * 0.8f).toInt()
                    layoutParams.height = (display.height * 0.9f).toInt()
                    shareDialog?.window!!.attributes = layoutParams
                    dImage = shareDialog?.findViewById(R.id.dImage)

                    shareDialog?.findViewById<TextView>(R.id.dTvSure)
                            ?.setOnClickListener {
                                showDialog()
                                Observable.just(bitmap)
                                        .subscribeOn(Schedulers.io())
                                        .map { v ->
                                            Uri.parse(MediaStore.Images.Media.insertImage(
                                                    contentResolver,
                                                    v,
                                                    null,
                                                    null))
                                        }
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe({ uri ->
                                                       disDialog()
                                                       val shareIntent = Intent()
                                                       shareIntent.action = Intent.ACTION_SEND
                                                       shareIntent.putExtra(Intent.EXTRA_STREAM,
                                                                            uri)
                                                       shareIntent.type = "image/*"
                                                       start(Intent.createChooser(shareIntent,
                                                                                  "分享到"))
                                                       shareDialog?.dismiss()
                                                   }) { t ->
                                            t.printStackTrace()
                                            disDialog()
                                            RxToast.error("分享失败")
                                        }
                            }
                    shareDialog?.findViewById<TextView>(R.id.dTvCancel)
                            ?.setOnClickListener {
                                bitmap.recycle()
                                shareDialog?.dismiss()
                            }
                }
        dImage?.setImageBitmap(bitmap)
        shareDialog?.show()
    }

    // --------------- Handler ---------------
    private val mHandler: Handler = object : Handler()
    {
        override fun handleMessage(msg: Message?)
        {
            super.handleMessage(msg)
            isFirst = false
        }
    }

    // --------------- EventBus ---------------
    @Subscribe
    fun onEvent(event: MainTypeItemVo)
    {
        setTabLayout(event.list)
    }

    private fun setTabLayout(list: List<MainItemVo>)
    {
        mTabLayout.removeOnTabSelectedListener(selectListener)
        mTabLayout.removeAllTabs()
        ids = arrayListOf()
        list.forEach {
            mTabLayout.addTab(mTabLayout.newTab().setText(it.proName))
            ids.add(it.id)
        }
        mTabLayout.tabMode = TabLayout.MODE_SCROLLABLE
        mTabLayout.addOnTabSelectedListener(selectListener)
        getRouteDetail(ids[0])
    }
}